from flask import render_template, g, redirect, jsonify, current_app, abort

from info import constants, db
from info.models import Category, News, User
from info.utils.common import user_login_data
from flask import request

from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blu


# 作者新闻列表
# 请求路径: /user/other_news_list
# 请求方式: GET
# 请求参数:p,user_id
# 返回值: errno,errmsg
@profile_blu.route('/other_news_list')
def other_news_list():
    """
    思路分析 :
    1.获取参数
    2.参数校验,为空判断,参数类型转换
    3.取出作者对象
    4.判断作者对象是否存在
    5.分页获取作者新闻列表
    6.获取到分页对象属性,总页数,当前页,当前页对象
    7.返回响应,携带数据
    :return:
    """
    # 1.获取参数
    page = request.args.get('p',1)
    author_id = request.args.get("user_id")

    # 2.参数校验,为空判断,参数类型转换
    if not author_id:
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 3.取出作者对象
    try:
        author = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取用户失败")

    # 4.判断作者对象是否存在
    if not author:
        return jsonify(errno=RET.NODATA,errmsg="作者不存在")

    # 5.分页获取作者新闻列表
    try:
        paginate = author.news_list.order_by(News.create_time.desc()).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询新闻失败")

    # 6.获取到分页对象属性,总页数,当前页,当前页对象
    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    news_list = []
    for item in items:
        news_list.append(item.to_dict())

    # 7.返回响应,携带数据
    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_list":news_list
    }
    return jsonify(errno=RET.OK,errmsg="获取成功",data=data)



# 作者详情界面
# 请求路径: /user/other
# 请求方式: GET
# 请求参数:id
# 返回值: 渲染other.html页面,字典data数据
@profile_blu.route('/other')
@user_login_data
def other_info():
    """
    思路分析:
    1.获取作者编号
    2.判断编号是否存在
    3.查询作者对象
    4.判断作者对象是否存在
    5.拼接数据,渲染页面
    :return:
    """
    # 1.获取作者编号
    author_id = request.args.get("id")

    # 2.判断编号是否存在
    if not author_id:
        abort(404)
        # return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    # 3.查询作者对象
    try:
        author = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询用户失败")

    # 4.判断作者对象是否存在
    if not author:
        abort(404)
        # return jsonify(errno=RET.NODATA,errmsg="作者不存在")

    # 4.2判断当前用户是否关注了该作者
    is_followed = False
    if g.user:
        if g.user in author.followers:
            is_followed = True


    # 5.拼接数据,渲染页面
    data = {
        "author_info":author.to_dict() if author else "",
        "user_info":g.user.to_dict() if g.user else "",
        "is_followed":is_followed
    }
    return render_template('news/other.html',data=data)


# 获取我的关注列表
# 请求路径: /user/user_follow
# 请求方式: GET
# 请求参数:p
# 返回值: 渲染user_follow.html页面,字典data数据
@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    """
    思路分析:
    1.获取参数
    2.参数类型转换
    3.分页查询数据
    4.获取分页对象属性,总页数,当前页,当前页对象
    5.对象列表转字典列表
    6.拼接数据返回页面渲染
    :return:
    """
    # 1.获取参数
    page = request.args.get("p",1)

    # 2.参数类型转换
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 3.分页查询数据
    try:
        paginate = g.user.followed.paginate(page,constants.USER_FOLLOWED_MAX_COUNT,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取用户失败")

    # 4.获取分页对象属性,总页数,当前页,当前页对象
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 5.对象列表转字典列表
    user_list = []
    for item in items:
        user_list.append(item.to_dict())

    # 6.拼接数据返回页面渲染
    data= {
        "totalPage":totalPage,
        "currentPage":currentPage,
        "user_list":user_list
    }
    return render_template('news/user_follow.html',data=data)


@profile_blu.route('/news_list')
@user_login_data
def news_list():
    user = g.user
    user_news = []
    current_page = 1
    total_page = 1
    page = request.args.get("p", 1)

    try:
        page  = int(page)
        paginate = News.query.filter_by(user_id=user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        user_news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_list = []
    for news in user_news:
        news_list.append(news.to_review_dict())

    data = {
        'news_list': news_list,
        'current_page': current_page,
        'total_page': total_page,
    }

    return render_template('news/user_news_list.html', data=data)

@profile_blu.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    if request.method == 'GET':
        categories = []
        try:
            # 获取所有的分类数据
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        # 定义列表保存分类数据
        categories_dicts = []

        for category in categories:
            # 获取字典
            cate_dict = category.to_dict()
            # 拼接内容
            categories_dicts.append(cate_dict)

        # 移除`最新`分类
        categories_dicts.pop(0)
        # 返回内容
        return render_template('news/user_news_release.html', data={"categories": categories_dicts})

    # 获取参数
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')

    # 校验参数
    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    # 创建新闻对象
    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content
    news.source = '个人发布'
    news.user_id = g.user.id
    news.status = 1  # 0代表审核通过，1代表审核中，-1代表审核不通过

    # 上传图片到七牛云
    try:
        imamg_name = storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传图片失败')

    news.index_image_url = constants.QINIU_DOMIN_PREFIX + imamg_name

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败" )

    return jsonify(errno=RET.OK, errmsg="发布成功")



@profile_blu.route('/collection')
@user_login_data
def user_collection():

    # 获取参数
    page = request.args.get("p", 1)

    # 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger(e)
        page = 1
    # 查询用户指定页数的收藏新闻
    user = g.user
    news_list = []
    total_page = 1
    current_page = 1
    try:
        paginate = user.collection_news.paginate(page ,constants.USER_COLLECTION_MAX_NEWS, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "collections": news_dict_li}


    return render_template('news/user_collection.html',data=data)


@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pass_info.html')

    # 1.获取参数
    data_dict = request.json
    old_password = data_dict.get('old_password')
    new_password = data_dict.get('new_password')


    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")


    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码不一致")

    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败" )

    return jsonify(errno=RET.OK, errmsg='保存成功')
    # 2.校验参数
    # 3.保存密码
    # 4.返回结果


@profile_blu.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pic_info.html', data={"user_info": user.to_dict()})
        # 1. 获取到上传的文件
    try:
        avatar_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件出错")

        # 2. 再将文件上传到七牛云
    try:
        url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")

    # 3. 将头像信息更新到当前用户的模型中

    # 设置用户模型相关数据
    user.avatar_url = url
    # 将数据保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户数据错误")

    # 4. 返回上传的结果<avatar_url>
    return jsonify(errno=RET.OK, errmsg="OK", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + url})


@profile_blu.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    if request.method == 'GET':
        return render_template('news/user_base_info.html', data={"user":g.user.to_dict()})

    # 代表是修改用户的数据
    # 1.取到传入的参数
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')

    if not all(['nick_name', 'signature', 'gender']):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    user = g.user
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    return jsonify(errno=RET.OK, errmsg='OK')






#展示个人中心
@profile_blu.route('/show_user_info')
@user_login_data
def show_user_info():
    user = g.user
    if not user:
        return redirect('/')

    data = {
        "user_info":user.to_dict() if user else ""
    }

    return render_template('news/user.html',data=data)